const http = require("../../../utils/request");
const areaList = require("../../../utils/moudle/ChineseAdministrativeRegion").data;
const pageTitleList = ['新增核实记录', '修改核实记录']

Page({
  data: {
    shake:true,
    isdelete: false,
    pageState: 0,//0：新增，1：修改
    pageTitle: null,
    isEdit: false,
    verifyType: null,
    //页面数据
    verifyObj: {
      code: "",
      policy_no: "",
      title: "",
      captureAddress: "",
      farmer: "",
      picture: [],
      capture_time: "",
      longitude: "",
      latitude: "",
    },
    //对话框
    dialogVisible: false,
    dialogTitle: '',
    dialogContent: '',
    //输入框
    verifyTitle: {//key改了，this.data.verifyObj也要改
      title: "标题",
      captureAddress: "位置",
      farmer: "养殖户",
      picture: "核实图片",
      // TODO:功能待开发
      // capture_time: "拍摄时间",
      // longitude:"经度",
      // latitude:"纬度",
    },
    phoneStatus: 'success',
    phoneErrorInfo: "",
    //上传图片
    uploadPictureFiles: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
  },
  /*
  * 绑定事件的函数
   */
  /* 对话框 */
  showDialog(title, content) {
    this.setData({
      dialogVisible: true,
      dialogTitle: title,
      dialogContent: content
    })
  },

  closeDialog(e) {
    this.setData({
      dialogVisible: false,
      dialogTitle: '',
      dialogContent: ''
    })
  },

  //输入框
  inputVerifyObj(event,) {
    //按确定的时候才做校验
    this.setData({
      verifyObj: { ...this.data.verifyObj, [event.target.id]: event.detail.value }
    })
  },

  //确定按钮
  //按钮为编辑则切换状态，为确定则校验信息并post
  tapConfirmOrEdit() {
    if (!this.canPostVerifyObj(this.data.verifyTitle)) {
      wx.showToast({
        title: '信息未填写完',
        icon: 'error'
      })
    } else {
      if (this.data.pageState == 0) {
        this.postVerification()
      } else if (this.data.pageState == 1) {
        this.putVerification()
      } else {
        wx.showModal({
          title: '错误',
          content: '页面状态错误',
          complete: (res) => { wx.navigateBack(2) }
        })
      }
    }
  },

  // 图片上传
  pushUploadPictureFiles(pictures) {
    const result = this.data.uploadPictureFiles
    for (let i in pictures) {
      result.push({
        url: pictures[i],
        name: 'uploaded1.png',
        type: 'image',
      })
    }
    this.setData({
      uploadPictureFiles: result
    })
  },
  addPicture(e) {
    const { files } = e.detail;
    this.postPicture(files[files.length - 1].url, this.data.uploadPictureFiles.length)
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.setData({
      uploadPictureFiles: files,
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { uploadPictureFiles } = this.data;
    let temppicture = this.data.verifyObj.picture
    temppicture.splice(index, 1)
    uploadPictureFiles.splice(index, 1);
    this.setData({
      uploadPictureFiles,
      verifyObj: { ...this.data.verifyObj, picture: temppicture }
    });
    console.log(uploadPictureFiles, temppicture)
  },

  /**
   * 切换页面状态（弃用：当前页面无需第二状态）
   */
  // changePageState() {
  //   if (this.data.pageState == 1) {
  //     this.setData({
  //       pageState: 0,
  //       pageTitle: pageTitleList[0]
  //     })
  //   }
  //   this.setData({
  //     isEdit: !this.data.isEdit,
  //   })
  // },

  /**
   * 请求函数
   */
  postVerification() {
    this.setData({
      shake: true,
    })
    // console.log('发送一条数据:', this.data.verifyObj);
    if(this.data.shake){
      http.postRequestBody(
        "/admin/verification",
        this.data.verifyObj,
        (res) => {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            confirmText: "我知道了",
            complete: (res) => {
              wx.navigateBack(2)
            }
          })
          this.setData({
            shake: false,
          })
        },
        (err) => {
          wx.showToast({
            title: '失败',
            icon: 'error'
          })
          console.log("增加养殖记录失败", res);
          this.setData({
            shake: false,
          })
        }
      );
    }else{
      wx.showToast({
        title: '不要重复点击！',
        icon: 'error'
      })
    }
  },
  putVerification() {
    http.putRequest(
      "/admin/verification",
      this.data.verifyObj,
      (res) => {
        console.log(res)
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel: false,
          confirmText: "我知道了",
          complete: (res) => {
            wx.navigateBack(2)
          }
        })
      },
      (err) => {
        wx.showModal({
          title: '提示',
          content: err.data.message,
          complete: (res) => {
            wx.navigateBack(2)
          }
        })
      }
    );
  },
  //传入一个图片url，上传图片，返回图片链接添加到uploadPictureFiles
  postPicture(pictureurl, index) {
    const task = wx.uploadFile({
      url: "https://37y5825u15.oicp.vip" + '/admin/cos/upload',
      filePath: pictureurl,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        console.log(res)
        this.setData({
          [`uploadPictureFiles[${index}].url`]: JSON.parse(res.data).data,
          [`uploadPictureFiles[${index}].status`]: 'done',
          [`verifyObj.picture`]: [...this.data.verifyObj.picture, JSON.parse(res.data).data]
        });
      },
      fail: (res) => {
        wx.showToast({
          title: '图片上传失败',
          icon: 'error'
        })
        this.setData({
          [`uploadPictureFiles[${index}].status`]: 'failed',
        });
      }
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`uploadPictureFiles[${index}].percent`]: res.progress,
        [`uploadPictureFiles[${index}].status`]: 'loading',
      });
    });
  },

  /**
 * 跳转函数
 */
  gotoPhoto() {
    wx: wx.navigateTo({
      url: '../detail',
      events: false,
      success: (result) => { },
      fail: (res) => { },
      complete: (res) => { },
    })
  },

  /**
   * 校验函数
   */
  /**
   * @private
   * @param {String || Array} this.data.verifyTitle
   */
  canPostVerifyObj(obj) {
    for (let i in obj) {
      if (i == 'picture' && obj[i].length == 0 || this.isNull(obj[i])) {
        console.log(i)
        return false
      }
    }
    return true
  },

  /**
   * @private
   * @param { !Array || !Object }this.data.verifyObj
   */
  isNull(val) {
    if (val == undefined || val == null || val == "") {
      return true;
    }
    return false;
  },
  //获取
  getCode(datas) {
    return datas.code
  },
  getType(obj) {
    return obj.type
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let app = getApp().globalData;
    let datas = app.photo_cultivation;
    let code = this.getCode(datas)
    let type = this.getType(app.photo_type);
    if (options.data != {}) {
      const pageState = 1
      this.setData({
        pageState: pageState,
        pageTitle: pageTitleList[pageState],
        isEdit: true,
        verifyObj: JSON.parse(options.data),
        verifyType: type
      })
      this.pushUploadPictureFiles(JSON.parse(options.data).picture)
    } else {
      const pageState = 0
      this.setData({
        pageState: pageState,
        pageTitle: pageTitleList[pageState],
        isEdit: true,
        verifyObj: { ...this.data.verifyObj, type: type, code: code },
        verifyType: type,
      })
    }

    //设置新增核实记录的页面状态

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})